<?php

namespace app\api\controller;

use app\api\model\Student;

class Base
{

    //注册功能
    public function register()
    {
        //传入学号，姓名，密码注册
        //校验参数
        $no = input('get.no');
        $name = input('get.name');
        $password = input('get.password');
        //判断数据是否填写完整，如果没有填写完整，输出错误信息
        if (empty($no) || empty($name) || empty($password)) {
            output_error('信息填写不完整，请重新填写');
        }
        //规则1：学号唯一
        //数据库模型查找学号字段，如果不为空，输出信息
        $data = Student::where('student_no', '=', $no)->find();
        if (!empty($data)) output_error('学号已经被注册');
        //规则2：密码md5加密
        $data = array();
        $data['student_no'] = $no;
        $data['student_name'] = $name;
        $data['student_token'] = '-1';
        $data['student_gender'] = '2';
        $data['add_time'] = time();
        $data['student_password'] = md5($password);
        Student::insert($data);
        output_data('1');
    }

    //找回密码
    public function findpass()
    {
        //通过学号，姓名重置密码
        $no = input('get.no');
        $name = input('get.name');
        $password = input('get.password');
        //判断数据是否填写完整，如果没有填写完整，输出错误信息
        if (empty($no) || empty($name) || empty($password)) {
            output_error('信息填写不完整，请重新填写');
        }
        $condition = array();
        $condition = ['student_no', '=', $no];
        $condition = ['student_name', '=', $name];
        $data = Student::where($condition)->find();
        if (empty($data)) output_error('学号与姓名不匹配');
        //规则1：密码md5加密
        Student::where('student_id', '=', $data['student_id'])
            ->update(array('student_password' => md5($password)));
        output_data('1');
    }

    //登录功能
    public function login()
    {
        //通过学号，密码登录，返回Token
        $no = input('get.no');
        $password = input('get.password');
        //判断数据是否填写完整，如果没有填写完整，输出错误信息
        if (empty($no) || empty($password)) {
            output_error('请将信息填写完整');
        }
        $condition = array();
        $condition = ['student_no', '=', $no];
        $condition = ['student_password', '=', md5($password)];
        $data = Student::where($condition)->find();
        if (empty($data)) output_error('学号与密码不匹配');
        //规则1：token由学号+当前时间戳md5加密生成
        $token = md5($no . time());
        Student::where('student_id', '=', $data['student_id'])
            ->update(array('student_token' => $token));
        output_data('1');
    }

}
